<template>
  <div class="category-container">
    <el-tree
      :data="categories"
      :props="defaultProps"
      node-key="id"
      :expand-on-click-node="false"
      :highlight-current="true"
      :default-expand-all="true"
      class="custom-tree"
    ></el-tree>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import axios from '../plugins/axios'

interface Category {
  id: number;
  name: string;
  parentId: number | null;
  children?: Category[];
}

const categories = ref<Category[]>([])
const defaultProps = {
  children: 'children',
  label: 'name'
}

const buildTree = (data: Category[]): Category[] => {
  const map = new Map<number, Category>()
  data.forEach(item => map.set(item.id, { ...item, children: [] }))

  const tree: Category[] = []
  data.forEach(item => {
    if (item.parentId === null) {
      tree.push(map.get(item.id)!)
    } else {
      map.get(item.parentId)!.children!.push(map.get(item.id)!)
    }
  })

  return tree
}

const fetchCategories = async () => {
  try {
    const response = await axios.get('/categories')
    categories.value = buildTree(response.data)
  } catch (error) {
    console.error('Failed to fetch categories:', error)
  }
}

onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.custom-tree .el-tree-node__content {
  margin-bottom: 10px;
  padding-left: 20px;
}

.custom-tree .el-tree-node {
  margin-bottom: 10px; /* 增加节点之间的上下间距 */
}

.custom-tree .el-tree-node.is-expanded > .el-tree-node__children {
  padding-left: 20px; /* 增加子节点的左边距 */
}
</style>